# coding:utf-8
# @Time : 2021/5/13 17:32 
# @Author : minuy
# @File : wallet.py
from flask import request

from app import login_auth, db
from app.api import api
from app.api.interface import api_result
from app.libs.number_tool import is_number


@api.route('/wallet/recharge', methods=['POST'])
@login_auth.login_required
def wallet_recharge():
    """
    充值
    :return:
    """
    user = login_auth.current_user
    # 兼容提交
    json_data = request.get_json()
    args_data = request.args
    if json_data:
        post_form = json_data
    else:
        post_form = args_data
    print(post_form)

    if post_form:
        money = post_form.get('money')
        password = post_form.get('password')

        if money and is_number(money) and password:

            if str(password)[0:6] != user.username[0:6]:
                print('密码错误', user.username[0:6], str(password)[0:6])
                return api_result(code=403, message='支付密码错误')

            try:
                money = int(money)
            except Exception as e:
                print('参数错误', money, e)
                return api_result(code=403, message='金额参数错误')

            user.coin = user.coin + money

            try:
                db.session.commit()
            except Exception as e:
                print('数据库错误', e)
                return api_result(code=500, message='数据库错误')
            print('充值成功', money, password, user.username)
            return api_result(code=200)
    return api_result(code=403, message='参数错误')


@api.route('/wallet/query')
@login_auth.login_required
def wallet_get():
    """
    查询
    :return:
    """
    user = login_auth.current_user
    if user:
        return api_result(data={
            'money': user.coin
        })
    return api_result(code=403, message='参数错误')


@api.route('/wallet/withdrawal', methods=['POST'])
@login_auth.login_required
def wallet_withdrawal():
    """
    提现
    :return:
    """
    user = login_auth.current_user
    if user:
        m = user.coin
        user.coin = 0
        try:
            db.session.commit()
        except Exception as e:
            print('数据库错误', e)
            return api_result(code=500, message='数据库错误')
        print('提现成功', m, user.coin)
        return api_result(code=200)
    return api_result(code=403, message='参数错误')
